#include <iostream>
#include <unistd.h>
#include <assert.h>
#include <cstring>
#include <sys/wait.h>

using namespace std;

int main()
{
    int pipefd[2] = {0};
    int n = pipe(pipefd);
    assert(n == 0);
    (void)n;

    pid_t id = fork();
    assert(id != -1);
    if (id == 0)
    {
        //子进程
        //读取操作，关闭写入
        close(pipefd[1]);
        char buffer[1024];//读取到这里
        ssize_t s = read(pipefd[0], buffer, sizeof(buffer) - 1);
        if (s > 0)
        {
            buffer[s] = 0;
            cout << "child get a message[" << getpid() << "] father : " << buffer << endl;
        }
        exit(-1);
    }
    //父进程
    //写入操作，关闭读取
    close(pipefd[0]);
    string message = "i am father";
    char send_buffer[1024*8];
    snprintf(send_buffer, sizeof(send_buffer), "%s[%d]", message.c_str(), getpid());
    write(pipefd[1], send_buffer, strlen(send_buffer));
    pid_t ret = waitpid(id, nullptr, 0);
    (void)ret;

    close(pipefd[1]);
    return 0;

}